﻿using Kingdee.BOS;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Const;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.NotePrint;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Core.Report.PlugIn;
using Kingdee.BOS.Core.ReportFilter;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.BOS.Web.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;

namespace DzInfo.Report.Print
{
     [Description("【列表插件】在单据列表套打导出简单账表PDF"), HotUpdate]
    public class ExportReportPDFListPlugIn : AbstractListPlugIn
    {
        /// <summary>
        /// 简单账表标识，这里用【采购订单执行明细表】作为例子
        /// </summary>
        private string _rptFormId = "PUR_PurchaseOrderDetailRpt";

        /// <summary>
        /// 简单账表过滤方案Id，通过T_BAS_FilterScheme查询得到
        /// </summary>
        private string _rptFilterSchemeId = "682292c65ff7f5";

        /// <summary>
        /// 账表的套打模板Id  select * from T_META_OBJECTTYPE where FBASEOBJECTID='PUR_PurchaseOrderDetailRpt'
        /// </summary>
        private string _rptTemplateId = "采购订单执行明细表";

        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterBarItemClick(e);

            if ("tbExportReportPDF".EqualsIgnoreCase(e.BarItemKey))
            {
                this.ExportReportPDF();
            }
        }

        private void ExportReportPDF()
        {
            ISysReportView rptView = null;
            ISysReportViewService rptService = null;
            try
            {
                // 获取账表元数据
                FormMetadata formMetadata = FormMetaDataCache.GetCachedFormMetaData(this.Context, this._rptFormId);
                // 获取简单账表资源服务提供器
                IResourceServiceProvider provider = GetSysReportServiceProvider();
                // 反射创建简单账表View
                string importViewClass = "Kingdee.BOS.Web.Report.SysReportView,Kingdee.BOS.Web";
                var dynService = CreateReportView(this.Context, formMetadata, this._rptFilterSchemeId, provider, importViewClass);
                rptView = dynService as ISysReportView;
                rptService = dynService as ISysReportViewService;
                if (rptView == null || rptService == null)
                    return;

                // 添加动态创建的账表View
                this.AddSessionView(rptView);

                // 创建套打导出参数
                var pExinfo = new PrintExportInfo();
                pExinfo.PageId = rptView.PageId;
                pExinfo.FormId = this._rptFormId;
                pExinfo.BillIds = new List<string>();
                pExinfo.TemplateIds = new List<string> { this._rptTemplateId };
                pExinfo.FileType = ExportFileType.PDF;
                pExinfo.ExportType = ExportType.ByPage;
                // 使用新版导出
                pExinfo.UsedCustomExportPDF = true;
                string dir = PathUtils.GetPhysicalPath(KeyConst.TEMPFILEPATH);
                pExinfo.FilePath = Path.Combine(dir, string.Format("{0}.pdf", DateTime.Now.ToString("yyyyMMdd_HHmmss")));
                rptService.ExportNotePrint(pExinfo);

                this.View.ShowMessage("导出成功");
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                // 移除动态创建的账表View
                if (rptView != null)
                    this.RemoveSessionView(rptView);
            }
        }

        private void RemoveSessionView(ISysReportView reportView)
        {
            var sessionManager = CommonSession.GetCurrent(this.Context.UserToken).SessionManager;
            sessionManager.Remove(reportView.PageId, reportView.GetType().Name);
        }

        private void AddSessionView(ISysReportView reportView)
        {
            var sessionManager = CommonSession.GetCurrent(this.Context.UserToken).SessionManager;
            sessionManager.GetOrAdd(reportView.PageId, reportView.GetType().Name, reportView);
        }

        private IDynamicFormView CreateReportView(Context ctx, FormMetadata metadata, string filterschemeid, IResourceServiceProvider provider, string reportViewClass)
        {
            var openParameter = CreateReportOpenParameter(ctx, metadata, filterschemeid);
            Type type = Type.GetType(reportViewClass);
            IDynamicFormViewService reportView = (IDynamicFormViewService)Activator.CreateInstance(type);
            reportView.Initialize(openParameter, provider);

            // 如果需要调整过滤条件，在这里修改
            // 例如：把采购组织改为其他的组织
            //var rptView = reportView as ISysReportView;
            //rptView.Model.FilterParameter.CustomFilter["PurchaseOrgIdList"] = "100003,135879";

            reportView.LoadData();

            return (IDynamicFormView)reportView;


        }

        private DynamicFormOpenParameter CreateReportOpenParameter(Context ctx, FormMetadata metadata, string filterschemeid)
        {
            var form = metadata.BusinessInfo.GetForm();
            SysReportOpenParameter openPara = new SysReportOpenParameter(form.Id, metadata.GetLayoutInfo().Id);
            openPara.Context = ctx;
            openPara.PageId = Guid.NewGuid().ToString();
            openPara.Status = OperationStatus.VIEW;
            openPara.FormMetaData = metadata;
            openPara.SetCustomParameter(FormConst.PlugIns, form.CreateFormPlugIns());
            openPara.SetCustomParameter(KeyConst.IsShowProcessBar, "0");
            openPara.SetCustomParameter(BOSConst.LIST_FILTERSCHEMEID, filterschemeid);
            openPara.ServiceName = form.FormServiceName;
            openPara.IsShowFilter = false;
            openPara.IsConnDetail = false;
            openPara.UseOrgId = 0;

            return openPara;

        }

        private IResourceServiceProvider GetSysReportServiceProvider()
        {
            FormServiceProvider provider = new FormServiceProvider();
            Type type = TypesContainer.GetOrRegister("Kingdee.BOS.Web.Report.SysReportView,Kingdee.BOS.Web");
            provider.Add(typeof(IDynamicFormView), Activator.CreateInstance(type));
            provider.Add(typeof(DynamicFormViewPlugInProxy), new SysReportViewPlugInProxy());
            provider.Add(typeof(DynamicFormModelPlugInProxy), new SysReportModelPlugInProxy());
            type = TypesContainer.GetOrRegister("Kingdee.BOS.Model.Report.SysReportModel,Kingdee.BOS.Model");
            provider.Add(typeof(IDynamicFormModelService), Activator.CreateInstance(type));
            type = TypesContainer.GetOrRegister("Kingdee.BOS.Model.ReportFilter.SysReportFilterModel,Kingdee.BOS.Model");
            provider.Add(typeof(ISysReportFilterModelService), Activator.CreateInstance(type));
            type = TypesContainer.GetOrRegister("Kingdee.BOS.Business.DynamicForm.DefaultValue.DefaultValueCalculator,Kingdee.BOS.Business.DynamicForm");
            provider.Add(typeof(IDefaultValueCalculator), Activator.CreateInstance(type));
            // 注册IDBModelService
            type = TypesContainer.GetOrRegister("Kingdee.BOS.Business.DynamicForm.DBModel.DBModelService,Kingdee.BOS.Business.DynamicForm");
            provider.Add(typeof(IDBModelService), Activator.CreateInstance(type));
            return provider;
        }
    }
}
